package cdu.javaendwork.Controller.Admin.User;

import cdu.javaendwork.dao.Universal;
import cdu.javaendwork.dao.impl.UniversalImpl;
import cdu.javaendwork.model.sqlModel.User;
import cdu.javaendwork.service.Impl.User.UserServiceImpl;
import cdu.javaendwork.service.Interface.User.UserService;
import cdu.javaendwork.util.ProNumber.ProNumBerHelper;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;

@WebServlet("/admin/admin_mod")
public class AdminModController extends HttpServlet {

    UserService userService=new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 根据id获取用户 如果没有adminid传入则先标记adminid为0
        String aid=req.getParameter("adminid");
        int adminid=(aid == null || aid.equals("")) ? 0 : Integer.parseInt(aid);
        //如果没有传入id 则说明是要修改自己的个人资料 将id改成自己
        if(adminid == 0)
        {
            HttpSession session = req.getSession();
            User me= (User)session.getAttribute("user");
            adminid = me.getId();
        }
        //将要修改资料的用户信息拿到jsp
        User user=userService.findById(adminid);
        req.setAttribute("user",user);

        // 跳转到修改管理员的界面
        req.getRequestDispatcher("admin_mod.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset = utf-8");
        User user=null;
        int AdId = 0;
        //拿到登录自己的的id
        HttpSession session = req.getSession();
        User me= (User)session.getAttribute("user");
        int myid = me.getId();
        //是否更新当前登录信息的标志位
        boolean flag = false;
        //保存照片位置
        String path = "/WEB-INF/photo";
        //获取真实对应的地址
        String photoUrl = req.getServletContext().getRealPath(path);
        System.out.println(photoUrl);
        //创建一个基于磁盘文件系统的工厂类
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //创建文件上传处理器
        ServletFileUpload upload =new ServletFileUpload(factory);
        try {
            //解析请求
            List<FileItem> items = upload.parseRequest(req);
            if(!items.isEmpty()){
                user = new User();
            }

            //创建迭代器，准备处理表单数据
            Iterator<FileItem> iterator = items.iterator();
            while (iterator.hasNext()){
                FileItem item = iterator.next();
                if(item.isFormField()){
                    if(item.getFieldName().equals("userid")){
                        user.setId(Integer.parseInt(item.getString("utf-8")));
                        AdId = Integer.parseInt(item.getString("utf-8"));
                        if(AdId == myid) flag = true;
                    }
                    if(item.getFieldName().equals("username")){
                        user.setUsername(item.getString("utf-8"));
//                        candidate.setName(new String(item.getString().getBytes("iso-8859-1"),"utf-8"));
                    }
                    if(item.getFieldName().equals("password")){
                        user.setPassword(item.getString("utf-8"));
                    }
                    if(item.getFieldName().equals("userprofile")){
                        user.setUserprofile(item.getString("utf-8"));
                    }
                    if(item.getFieldName().equals("phone")){
                        user.setPhone(item.getString("utf-8"));
                    }
                }else {

                    String fileName = item.getName();
                    if (fileName == null || fileName == "")
                    {
                        User nowUser = userService.findById(user.getId());
                        user.setPhoto(nowUser.getPhoto());
                    }else {
                        //防止重复的日期前缀
                        ProNumBerHelper proNumBerHelper = new ProNumBerHelper();
                        String pro = proNumBerHelper.getProNumBerForDate(new Timestamp(new java.util.Date().getTime()).toString());
                        File file = new File(photoUrl+"//"+pro+fileName);
                        item.write(file);
                        user.setPhoto(req.getContextPath()+path+"/"+pro+fileName);
                    }

                }
            }
        } catch (Exception e) {
            System.out.println("上传文件出错："+e.getMessage());
        }

        PrintWriter out = resp.getWriter();
        UserService userService=new UserServiceImpl();
        Universal universal=new UniversalImpl();


        if(user.getUsername()==null||user.getPassword()==null||user.getUsername().equals("")||user.getPassword().equals("")){
            out.println("<script>alert('修改失败!信息不能为空！');window.location.href='"+req.getContextPath()+"/admin/admin_mod?adminid="+AdId+"'</script>");
        }
        else {
            if(!userService.update(user.getId(),user.getUsername(),user.getPassword(),user.getPhoto(),user.getUserprofile(),user.getPhone(),2)){
                out.println("<script>alert('修改失败！');window.location.href='"+req.getContextPath()+"/admin/admin_mod?adminid="+AdId+"'</script>");
            }else{
                if(flag) session.setAttribute("user",user);
                out.println("<script>alert('修改成功！');window.location.href='"+req.getContextPath()+"/admin/admin_list'</script>");
            }
        }


    }
}
